package com.freecloud.whispered.auth.utils;

import cn.hutool.core.util.ObjectUtil;
import com.freecloud.framework.exceptions.RRException;
import com.freecloud.whispered.auth.entity.SysUserEntity;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Shiro工具类
 * 
 * @author maomao
 * @email 138383877@qq.com
 */
public class ShiroUtils {

	protected static Logger logger = LoggerFactory.getLogger(ShiroUtils.class);

	public static Session getSession() {
		return SecurityUtils.getSubject().getSession();
	}

	public static Subject getSubject() {
		return SecurityUtils.getSubject();
	}

	public static SysUserEntity getUserEntity() {
		return (SysUserEntity) SecurityUtils.getSubject().getPrincipal();
	}

	public static Long getUserId() {
		return getUserEntity().getUserId();
	}
	
	public static void setSessionAttribute(Object key, Object value) {
		getSession().setAttribute(key, value);
	}

	public static Object getSessionAttribute(Object key) {
		return getSession().getAttribute(key);
	}

	public static boolean isLogin() {
		return SecurityUtils.getSubject().getPrincipal() != null;
	}

	public static void logout() {
		SecurityUtils.getSubject().logout();
	}
	
	public static String getKaptcha(String key) {
		logger.info("getKaptcha : {}",ShiroUtils.getSession().getId());
		Object obj = getSessionAttribute(key);
		if(ObjectUtil.isEmpty(obj))
		{
			logger.error("getKaptcha is empty !! {}",key);
			throw new RRException("验证码错误！");
		}
		String kaptcha = obj.toString();
		getSession().removeAttribute(key);
		return kaptcha;
	}

}
